#include "download_file.h"
#include <curl/curl.h>

///////////////////////////////////////////////////////////////////////////////

// #define FILE_TRACE

#include "file_trace.h"

///////////////////////////////////////////////////////////////////////////////

//------------------------------------------------------------------------------
// static functions prototypes
//------------------------------------------------------------------------------

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream);

//------------------------------------------------------------------------------
// public functions
//------------------------------------------------------------------------------

int DOWNLOAD_File(char* url, char* destination_path)
{
	CURL* curl_handle;
	FILE* pagefile;
	CURLcode ret = curl_global_init(CURL_GLOBAL_ALL);
    
	curl_handle = curl_easy_init();
	if (curl_handle == NULL)
    {
        F_ERROR(("no cUrl handle!\n"));
        goto exit;
    }

	ret = curl_easy_setopt(curl_handle, CURLOPT_URL, url);
	ret = curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
 	pagefile = fopen(destination_path, "wb");
	
	if (pagefile)
	{
	    ret = curl_easy_setopt(curl_handle, CURLOPT_FILE, pagefile);
	    ret = curl_easy_perform(curl_handle);
  	    fclose(pagefile);
	}
    else
    {
        F_ERROR(("failed to open the file...\n"));    
    }

	// done
	curl_easy_cleanup(curl_handle);

exit:

    F_PRINT(("end\n"));
    
    return ret;
}

//------------------------------------------------------------------------------
// static functions
//------------------------------------------------------------------------------

static size_t write_data(void* ptr, size_t size, size_t nmemb, void *stream)
{
	return fwrite(ptr, size, nmemb, (FILE *)stream);
}
